//
//  QPNetWork.swift
//  QianPing
//
//  Created by yanglipeng on 2018/11/23.
//  Copyright © 2018 yanglipeng. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON
import Result
import ObjectMapper
import MJRefresh
class QPNetWork {
    
//    401  token不能为空
//    403  token不存在或已过期，请重新登录
    
    // 请求成功的回调
    typealias successCallback = (_ result: JSON) -> Void
    // 请求失败的回调
    typealias failureCallback = (_ error: MoyaError) -> Void
    
     typealias Progress = ((Double, Bool) -> Void)
    // 发送网络请求
    static func request<T: TargetType>(
        target: T,
        success: @escaping successCallback,
        failure: @escaping failureCallback
        ) {
        
        let provider = MoyaProvider(endpointClosure: { (target: T) -> Endpoint in
            let url = URL(target: target).absoluteString
            QPLog(url, target)
            
            return Endpoint(url: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers)
        })
        
        provider.request(target) { result in
            
            if logConfig.request{
                QPLog(target)
            }
            switch result {
            case let .success(moyaResponse):
            
                let responseData = JSON(moyaResponse.data).dictionaryValue
                
                if responseData["code"] == "100" {
                    //是否打印返回数据
                    if logConfig.response {
                        QPLog(JSON(moyaResponse.data).dictionaryValue)
                    }
                    if let resultData = responseData["result"] {
                        success(resultData)
                    } else {
                        success(JSON(responseData))
                    }
                } else if responseData["code"] == "10000" {
//                    UserDefaults.standard[ConstString.UserId] = nil
//                    UserDefaults.standard[ConstString.HasSketch] = nil
//                    UserDefaults.standard[ConstString.Token] = nil
//                    UserDefaults.standard[ConstString.PhoneNumber] = nil
                    QPLog(String(data:moyaResponse.data, encoding: .utf8) ?? "")
                    failure(MoyaError.jsonMapping(moyaResponse))
                } else if responseData["code"] == "403" {
                    
                    //token不存在或已过期，请重新登录
//                    UserDefaults.standard[ConstString.Token] = nil
//                    UserDefaults.standard[ConstString.PhoneNumber] = nil
                    QPLog(String(data:moyaResponse.data, encoding: .utf8) ?? "")
                    failure(MoyaError.jsonMapping(moyaResponse))
                }else {
                    QPLog(String(data:moyaResponse.data, encoding: .utf8) ?? "")
                    failure(MoyaError.jsonMapping(moyaResponse))
                }
                
            case let .failure(error):
                failure(error)
            }
        }
    }

    // 发送网络请求
    static func  requestList<T: TargetType, U: Mappable>(
        target: T,
        tableView: UIScrollView,
        success: @escaping (_ result: [U]) -> Void,
        failure: @escaping failureCallback
        ) {
        
        let provider = MoyaProvider(endpointClosure: { (target: T) -> Endpoint in
            let url = URL(target: target).absoluteString
            QPLog(url, target)
            
            return Endpoint(url: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers)
        })
        
        provider.request(target) { result in
            
            if logConfig.request{
                QPLog(target)
            }
            switch result {
            case let .success(moyaResponse):
                if tableView.mj_header != nil {
                    tableView.mj_header.endRefreshing()
                }
                
                //是否打印返回数据
                if logConfig.responselist {
                    QPLog(JSON(moyaResponse.data).dictionaryValue)
                }
                let responseData = JSON(moyaResponse.data).dictionaryValue
                
                if responseData["code"] == "100" {
//                    success(responseData["result"]!)
                    if let result = responseData["result"] {
            
                        let newArray = result.dictionaryValue["list"]?.arrayValue.map({ (json) -> U in
                        return U(JSON: json.dictionaryObject!)!
                        })
              
                        
                        if let isLast = result.dictionaryValue["isLastPage"]?.boolValue {
                            if isLast {
                                tableView.mj_footer?.endRefreshingWithNoMoreData()
                            } else {
                                
                                tableView.mj_footer?.endRefreshing()
                            }
                        }
                        success(newArray!)
                    }
                    
                } else if responseData["code"] == "10000" {
//                    UserDefaults.standard[ConstString.UserId] = nil
//                    UserDefaults.standard[ConstString.HasSketch] = nil
//                    UserDefaults.standard[ConstString.Token] = nil
//                    UserDefaults.standard[ConstString.PhoneNumber] = nil
                } else {
                    failure(MoyaError.jsonMapping(moyaResponse))
                }
                
            case let .failure(error):
                failure(error)
                tableView.mj_header?.endRefreshing()
                tableView.mj_footer?.endRefreshing()
            }
        }
    }
    
    static let provide = MoyaProvider(endpointClosure: { (target: QPCommonService) -> Endpoint in
        let url = URL(target: target).absoluteString
        QPLog(url, target)
        
        return Endpoint(url: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers)
    })
    
    static func download(
        filePath: String,
        downloadDestination: @escaping DownloadDestination,
        progress: @escaping Progress,
        success: @escaping ((_ result: Response) -> Void),
        failure: @escaping failureCallback
        ) {
        provide.request(.download(filePath: filePath, downloadDestination: downloadDestination), callbackQueue: DispatchQueue.main, progress: {
            
            progress($0.progress, $0.completed)
            
        }) { result in
            switch result {
            case let .success(moyaResponse):
                success(moyaResponse)
                
            case let .failure(error):
                failure(error)
            }
        }
    }
    
    static var baseUrl: URL {
        get {
            #if DEBUG
            return URL(string:BaseURL.BaseTest)!
            #else
            return URL(string:BaseURL.BaseOfficial)!
            #endif
        }
    }   
    
    static var loginUrl: URL {
        get {
            #if DEBUG
            return URL(string:BaseURL.LoginTest)!
            #else
            return URL(string:BaseURL.LoginOfficial)!
            #endif
        }
        
    }

    static var headers: [String: String] {
        get {
            let token = UserDefaults.standard[ConstString.Token]
            var headers = [
                "loginType": "QianPing",
                "X-Requested-With": "XMLHttpRequest"
            ]
          
//            if token != nil {
                 headers["Authorization"] = token as! String
//            }else{
//                //如果有临时token 使用临时token
//                if  QPLoginManager.shared.tempToken.count > 1{
//                     headers["Authorization"] = QPLoginManager.shared.tempToken
//                }
//            }
            return headers
        }
    }
}
